#include "spreadsheetundocommand.h"

//单个单元格修改
SpreadsheetUndoCommand::SpreadsheetUndoCommand(SpreadsheetModel *model, const QModelIndex &index,
                                               const QVariant &oldValue, const QVariant &newValue,
                                               QUndoCommand *parent)
    : QUndoCommand(parent),
    m_index(index),
    m_oldValue(oldValue),
    m_newValue(newValue),
    m_isBatch(false),
    m_model(model)
{
    //设置命令的显示文本为 "Cell Edit"，这会在撤销/重做菜单中显示
    setText("Cell Edit");//单个单元格修改
}
//批量单元格修改
SpreadsheetUndoCommand::SpreadsheetUndoCommand(SpreadsheetModel *model,
                                               const QMap<QModelIndex, QPair<QVariant, QVariant>>& changes,
                                               QUndoCommand *parent)
    : QUndoCommand(parent),
    m_changes(changes),
    m_isBatch(true),
    m_model(model)
{
    setText("Batch Edit");//批量单元格修改
}

// 实现撤销操作
void SpreadsheetUndoCommand::undo()
{
    if (!m_model) return;

    m_model->beginUndoRedo();
    if (m_isBatch) {
        for (auto it = m_changes.constBegin(); it != m_changes.constEnd(); ++it) {
            if (it.key().isValid()) {
                m_model->setData(it.key(), it.value().first, Qt::EditRole);
            }
        }
    } else if (m_index.isValid()) {
        m_model->setData(m_index, m_oldValue, Qt::EditRole);
    }
    m_model->endUndoRedo();
}

// 实现重做操作
void SpreadsheetUndoCommand::redo()
{

    if (!m_model) return;

    m_model->beginUndoRedo();
    if (m_isBatch) {
        for (auto it = m_changes.constBegin(); it != m_changes.constEnd(); ++it) {
            if (it.key().isValid()) {
                m_model->setData(it.key(), it.value().second, Qt::EditRole);
            }
        }
    } else if (m_index.isValid()) {
        m_model->setData(m_index, m_newValue, Qt::EditRole);
    }
    m_model->endUndoRedo();
}
